<?php
/**
 * PHPECS社交电商系统，使用thinkphp框架+MySQL数据库编写的小程序商城系统，基于LGPL协议开源授权
 * @package phpecs
 * @author qq(123865789)
 * @copyright 2018-2020 深圳塔灯网络科技有限公司
 * @version 2.0
 * @license http://www.phpecs.com/lgpl.html phpecs开源授权协议：GNU Lesser General Public License
 **/
namespace app\hgapi\controller;
use app\hgapi\model\market\MarketBack;
use app\hgapi\model\market\MarketLikes;
use app\hgapi\model\market\MarketPurchase;
use app\hgapi\model\market\MarketSpell;
use app\hgapi\model\market\MarketBargain;
use app\hgapi\model\market\MarketSeckill;
use app\hgapi\model\user\UserChoose;
use app\hgapi\model\activity\ActivityClock;
use app\hgapi\model\activity\ActivityRecharge;
use app\hgapi\model\store\StoreProductCoupon;
use app\hgapi\model\store\StoreProduct;
use app\hgapi\model\system\Site;
use app\hgapi\model\user\UserCheck;
use app\hgapi\model\user\UserGoldRecord;
use app\hgapi\model\store\StoreOrder;
use app\hgapi\model\store\StoreOrderList;
use app\hgapi\model\goods\GoodsPackage;
use app\hgapi\model\user\UserPackageRecord;
use app\hgapi\model\user\UserRecord;
use app\hgapi\model\user\UserCoupon;
use app\hgapi\model\user\UserPackage;
use app\hgapi\model\user\User;

class PayApi extends ProductApi{

    /**
     * 支付
     */
    public function pay(){
        $openid = input('openid'); //用户openid
        $uid = input('uid'); //用户id
        $shop = json_decode(input('shop'), true); //下单商品
        $address = json_decode(input('address'), true); //下单地址
        $message = input('message'); //备注
        $ling = input('ling'); //是否为领取商品
        $cid = input('cid'); //优惠券
        $kalman = input('kalman'); //卡密
        $time = date('YmdHis');
        $ord_id = "$time$uid"; //订单号
        $newShop = [];
        $total_price = 0;
        $freight = 0;
        foreach ($shop as $k => $v){
            $find = StoreProduct::getProductInfo(['id' => $v['id']], '');
            if (!$find){ //如果有不存在的就跳出循环
                errorCode('部分商品已下架或被删除');
            }elseif ($find['status'] == 1){ //如果有下架的也跳出循环
                errorCode('部分商品已下架或被删除');
            }
            //运费
            if ($find['ftype'] == 1){
                $freight += $find['freight'];
            }
            //参数值
            $value = json_decode($find['value'], true);
            if ($value){
                foreach ($value as $key => $val){
                    if ($val['group'] == $v['group']){
                        $newShop[$k]['id'] = $find['id'];
                        $newShop[$k]['group'] = $val['group'];
                        $newShop[$k]['price'] = $this->buling($val['price']);
                        $newShop[$k]['num'] = $v['num'];
                        $total_price += $val['price'] * $v['num']; //所有商品的价格
                    }
                }
            }else{
                $newShop[$k]['id'] = $find['id'];
                $newShop[$k]['price'] = $this->buling($find['price']);
                $newShop[$k]['num'] = $v['num'];
                $total_price += $find['price'] * $v['num']; //所有商品的价格
            }
        }
        //查出会员等级优惠
        $zhe = User::selUserZhe($uid);
        if ($zhe) {
            $news_price = $total_price > 0.01 ? $total_price * $zhe / 100 : $total_price;
            $benefit = $total_price - $news_price;
        }else{
            $news_price = $total_price;
        }
        //卡密直接领取
        $kashop = StoreProduct::getProductInfo(['id' => $shop[0]['id']], '');
        if ($kalman && $kashop['is_open']){
            $ka = explode("\n", $kashop['kalman']);
            if (in_array($kalman, $ka)){
                if ($kashop['offset'] == 0){
                    $dixiao = ($news_price - $kashop['price']) < 0 ? 0 : ($news_price - $kashop['price']);
                    $benefit = $total_price - $dixiao;
                    //删除当前卡密
                    foreach ($ka as $k => $v){
                        if($kalman == $v) unset($ka[$k]);
                    }
                    $ka = implode("\n", $ka);
                    StoreProduct::upField(['id' => $shop[0]['id']], 'kalman', $ka);
                    //如果优惠后的价格为0则直接添加订单
                    if (($dixiao + $freight) == 0){
                        //创建订单
                        $order = array(
                            'order' => $ord_id, //订单号
                            'uid' => $uid, //下单用户
                            'time' => time(), //下单时间
                            'username' => $address['name'], //收货人
                            'phone' => $address['tel'], //收货手机号
                            'address' => $address['province'] . $address['city'] . $address['county'] . $address['detail'], //收货详细地址
                            'money' => $total_price + $freight, //订单总额
                            'price' => $total_price,
                            'status' => 1, //直接通过
                            'freight' => $freight, //运费
                            'message' => $message, //用户留言
                            'ling' => 1, //是否为领取商品
                            'benefit' => $benefit,
                            'cid' => $cid,
                        );
                        $oid = StoreOrder::add($order);
                        //创建订单数据
                        foreach ($shop as $k => $v){
                            $orderlist = [
                                'oid' => $oid, //关联订单数据id
                                'pid' => $v['id'], //商品id
                                'spec' => $v['group'], //商品规格
                                'unit' => $v['price'], //商品单价
                                'num' => $v['num'], //购买数量
                            ];
                            StoreOrderList::add($orderlist);
                        }
                        //查出购买订单数据并修改
                        $orderlist = StoreOrderList::selOrderList(['oid' => $oid]);
                        foreach ($orderlist as $k => $v){
                            $product = StoreProduct::getProductInfo(['id' => $v['pid']], 'stock, volume, value');
                            $value = json_decode($product['value'], true);
                            if ($value){ //如果有选项则减少选项的库存
                                foreach ($value as $key => $val){
                                    if ($v['spec'] == $val['group']){ //相同的值减少
                                        $value[$key]['stock'] = $val['stock'] - $v['num'];
                                    }
                                }
                            }
                            $up = [
                                'stock' => $product['stock'] - $v['num'], //减少总库存
                                'volume' => $product['volume'] + 1, //增加销量
                                'value' => json_encode($value), //产品规格减少库存
                            ];
                            StoreProduct::upProduct(['id' => $v['pid']], $up);
                        }
                        errorCode(['code' => 2]);
                    }
                }else{
                    $newMoney = $total_price - $kashop['offset'];
                    $benefit = $total_price - $newMoney;
                }
            }
        }else{
            //优惠券
            if ($cid){
                $time = time();
                $u_cou = UserCoupon::getUserCoupon(['id' => $cid]);
                $coupon = StoreProductCoupon::getCoupon(['id' => $u_cou['cid']], '');
                if ($coupon['term'] == '0'){ //0为指定开始结束时间
                    $valid = explode(' - ', $coupon['valid']);
                    $start = strtotime($valid[0]);
                    $end = strtotime($valid[1]);
                    //判断当前优惠券是否在指定时间使用
                    if ($time >= $start && $time <= $end && ($coupon['doorsill'] == '0' ? true : $total_price >= $coupon['full'] ? true : false)){
                        if ($coupon['form'] == 0){
                            $benefit = $total_price - ($news_price - $coupon['discount'] <= 0 ? 0.01 : $news_price - $coupon['discount']);
                        }else{
                            $benefit = $total_price - round($news_price * $coupon['discount'] / 10, 2);
                        }
                    }
                }else{ //多少天内使用
                    if (($u_cou['time'] + $coupon['valid'] * 24 * 60 * 60) > $time && ($coupon['doorsill'] == '0' ? true : $total_price >= $coupon['full'] ? true : false)){ //在指定时间内
                        if ($coupon['form'] == 0){
                            $benefit = $total_price - ($news_price - $coupon['discount'] <= 0 ? 0.01 : $news_price - $coupon['discount']);
                        }else{
                            $benefit = $total_price - round($news_price * $coupon['discount'] / 10, 2);
                        }
                    }
                }
            }
        }
        //创建订单
        $order = array(
            'order' => $ord_id, //订单号
            'uid' => $uid, //下单用户
            'time' => time(), //下单时间
            'username' => $address['name'], //收货人
            'phone' => $address['tel'], //收货手机号
            'address' => $address['province'] . $address['city'] . $address['county'] . $address['detail'], //收货详细地址
            'money' => $ling == 2 ? $freight : $total_price + $freight, //订单总额 (商品总价加运费)
            'price' => $total_price,
            'status' => 0, //待付款
            'freight' => $freight, //运费
            'message' => $message, //用户留言
            'ling' => $ling, //是否为领取商品
            'benefit' => $benefit ? $benefit : 0.00,
            'cid' => $cid,
        );
        $oid = StoreOrder::add($order);
        //创建订单数据
        foreach ($shop as $k => $v){
            $orderlist = [
                'oid' => $oid, //关联订单数据id
                'pid' => $v['id'], //商品id
                'spec' => $v['group'], //商品规格
                'unit' => $v['price'], //商品单价
                'num' => $v['num'], //购买数量
            ];
            StoreOrderList::add($orderlist);
        }
        // 订单数据
        $order = array(
            'body' => '购买商品', //商品描述（需要根据自己的业务修改）
            'total_fee' => ($ling == 2 ? $freight : $total_price + $freight - $benefit) * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
            'out_trade_no' => $ord_id, //订单号（需要根据自己的业务修改）
            'trade_type' => 'JSAPI', //JSAPI公众号支付
            'openid' => $openid //获取到的openid
        );
        // 统一下单 获取prepay_id
        vendor('WeChatPay.XcxPay');
        $pay = new \XcxPay();
        $unified_order = $pay->unifiedOrder($order, config('XCX_CONFIG.SHOP'));
        $secret = secret();
        // 组合jssdk需要用到的数据
        $data = array(
            'appId' => $secret['appid'], //appid
            'timeStamp' => strval(time()), //时间戳
            'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
            'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
            'signType' => 'MD5'//加密方式
        );
        // 生成签名
        $data['paySign'] = $pay->makeSign($data);
        successCode(['code' => 1, 'data' => $data, 'prepay_id' => $unified_order['prepay_id'], 'oid' => $oid]);
    }

    /**
     * 活动订单支付
     */
    public function clock_pay(){
        $openid = input('openid'); //用户openid
        $uid = input('uid'); //用户id
        $clock_id = input('clock_id'); //下单活动
        $address = json_decode(input('address'), true); //下单地址
        $time = date('YmdHis');
        $ord_id = "$time$uid"; //订单号
        $clock = ActivityClock::getClock(['id' => $clock_id]);
        if ($clock) $clock = $clock->toArray();
        //查出是否已经挑战
        $is = StoreOrder::getOrder(['uid' => $uid, 'active_id' => $clock_id, 'type' => 1], '');
        if ($is){
            errorCode('你已经参加了此活动');
        }
        if ($clock['bao'] == 0){
            errorCode('此活动已暂停报名');
        }
        //创建订单
        $order = array(
            'order' => $ord_id, //订单号
            'uid' => $uid, //下单用户
            'active_id' => $clock_id, //挑战活动
            'time' => time(),
            'username' => $address['name'], //收货人
            'phone' => $address['tel'], //收货手机号
            'address' => $address['province'] . $address['city'] . $address['county'] . $address['detail'], //收货详细地址
            'money' => $clock['price'] + $clock['freight'], //订单总额
            'price' => $clock['price'], //待付款
            'freight' => $clock['freight'], //运费
            'benefit' => $clock['benefit'], //优惠
            'status' => 0,
            'ling' => 2,
            'type' => 1,
        );
        $oid = StoreOrder::add($order);
        $orderlist = [
            'oid' => $oid, //关联订单数据id
            'pid' => $clock['pid'], //商品id
            'unit' => $clock['price'], //商品单价
            'num' => 1, //购买数量
        ];
        StoreOrderList::add($orderlist);
        // 订单数据
        $order = array(
            'body' => '参加打卡活动', //商品描述（需要根据自己的业务修改）
            'total_fee' => ($clock['price'] + $clock['freight']) * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
            'out_trade_no' => $ord_id, //订单号（需要根据自己的业务修改）
            'trade_type' => 'JSAPI', //JSAPI公众号支付
            'openid' => $openid //获取到的openid
        );
        // 统一下单 获取prepay_id
        vendor('WeChatPay.XcxPay');
        $pay = new \XcxPay();
        $unified_order = $pay->unifiedOrder($order, config('XCX_CONFIG.CLOCK'));
        $secret = secret();
        // 组合jssdk需要用到的数据
        $data = array(
            'appId' => $secret['appid'], //appid
            'timeStamp' => strval(time()), //时间戳
            'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
            'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
            'signType' => 'MD5'//加密方式
        );
        // 生成签名
        $data['paySign'] = $pay->makeSign($data);
        successCode(['code' => 1, 'data' => $data, 'oid' => $oid, 'prepay_id' => $unified_order['prepay_id']]);
    }

    /**
     * 重新支付
     */
    public function again(){
        $openid = input('openid');
        $id = input('id'); //订单id
        $find = StoreOrder::getOrder(['id' => $id], ''); //查出订单数据
        // 订单数据
        $order = array(
            'body' => $find['type'] == 1 ? '参加打卡活动' : '购买商品', //商品描述（需要根据自己的业务修改）
            'total_fee' => ($find['money'] - $find['benefit']) * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
            'out_trade_no' => $find['order'], //订单号（需要根据自己的业务修改）
            'trade_type' => 'JSAPI', //JSAPI公众号支付
            'openid' => $openid //获取到的openid
        );
        // 统一下单 获取prepay_id
        vendor('WeChatPay.XcxPay');
        $pay = new \XcxPay();
        switch ($find['type']){
            case 0:
                $hui = config('XCX_CONFIG.SHOP');
                break;
            case 1:
                $hui = config('XCX_CONFIG.CLOCK');
                break;
            case 2:
                $hui = config('XCX_CONFIG.BARGAIN');
                break;
            case 3:
                $hui = config('XCX_CONFIG.SPELL');
                break;
            case 4:
                $hui = config('XCX_CONFIG.SECKILL');
                break;
            case 5:
                $hui = config('XCX_CONFIG.BACK');
                break;
            case 6:
                $hui = config('XCX_CONFIG.PURCHASE');
                break;
            case 7:
                $hui = config('XCX_CONFIG.LIKES');
                break;
            default:
                $hui = config('XCX_CONFIG.SHOP');
                break;
        }
        $unified_order = $pay->unifiedOrder($order, $hui);
        $secret = secret();
        // 组合jssdk需要用到的数据
        $data = array(
            'appId' => $secret['appid'], //appid
            'timeStamp' => strval(time()), //时间戳
            'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
            'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
            'signType' => 'MD5'//加密方式
        );
        // 生成签名
        $data['paySign'] = $pay->makeSign($data);
        successCode($data);
    }

    /**
     * 充值佣金
     */
    public function chong_gold(){
        $openid = input('openid'); //用户openid
        $id = input('id'); //用户id
        $num = input('num');
        $stage = input('stage');
        $gold = input('gold');
        $cid = input('cid');
        $time = date('YmdHis');
        $ord_id = "$time$id"; //订单号
        //创建订单
        $data = array(
            'order' => $ord_id, //订单号
            'uid' => $id,
            'num' => $num,
            'gold' => $gold,
            'time' => time(),
            'status' => 0,
            'cid' => $cid
        );
        UserGoldRecord::add($data);
        // 订单数据
        $order = array(
            'body' => '充值佣金', //商品描述（需要根据自己的业务修改）
            'total_fee' => $num * $stage * $gold * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
            'out_trade_no' => $ord_id, //订单号（需要根据自己的业务修改）
            'trade_type' => 'JSAPI', //JSAPI公众号支付
            'openid' => $openid //获取到的openid
        );
        // 统一下单 获取prepay_id
        vendor('WeChatPay.XcxPay');
        $pay = new \XcxPay();
        $unified_order = $pay->unifiedOrder($order, config('XCX_CONFIG.GOLD'));
        $secret = secret();
        // 组合jssdk需要用到的数据
        $data = array(
            'appId' => $secret['appid'], //appid
            'timeStamp' => strval(time()), //时间戳
            'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
            'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
            'signType' => 'MD5'//加密方式
        );
        // 生成签名
        $data['paySign'] = $pay->makeSign($data);
        successCode(['code' => 1, 'data' => $data]);
    }

    /**
     * 买单
     */
    public function check(){
        $id = input('id'); //商家id
        $uid = input('uid'); //用户id
        $fang = input('fang'); //用户id
        $money = input('money'); //买单金额
        $openid = input('openid'); //用户openid
        $zhe = Site::getSite('give, cashback'); //赠送和返回的使用折扣信息
        $find = User::getUserInfo(['id' => $uid], 'balance, give, cashback, sure'); //我的余额
        //抵扣赠送余额
        $zeng = $money * $zhe['give'] / 100;
        if ($zeng > $find['give']) { //如果超过剩余赠送余额则抵扣最大赠送余额
            $zeng = $find['give'];
        }
        //增加可提现余额
        $ti = $money * $zhe['cashback'] / 100;
        if ($ti > $find['cashback']) { //如果超过剩余返现余额则抵扣最大返现余额
            $ti = $find['cashback'];
        }
        //实付
        $shg = $money - $zeng;
        if ($fang == 1){ //余额支付
            if ($find['balance'] < $shg){ //我的余额小于实付
                errorCode('余额不足');
            }else{
                //修改我的余额
                $data = [
                    'balance' => $find['balance'] - $shg, //剩余余额
                    'give' => $find['give'] - $zeng, //剩余赠送余额
                    'cashback' => $find['cashback'] - $ti, //剩余返现余额
                    'sure' => $find['sure'] + $ti //增加可提现余额
                ];
                $re = User::upUserInfo(['id' => $uid], $data);
                //给商家增加佣金
                User::incField($id, 'gold', $money);
                if ($re){
                    // 获取当前时间戳
                    $time = date('YmdHis');
                    $ord_id = "E-$time-$uid";
                    //增加买单记录
                    $mai = [
                        'order' => $ord_id,
                        'shop_id' => $id,
                        'uid' => $uid,
                        'time' => time(),
                        'status' => 1,
                        'money' => $money,
                        'zeng' => $zeng,
                        'shi' => $shg,
                        'ti' => $ti,
                        'type' => 0
                    ];
                    UserCheck::add($mai);
                    successCode('买单成功');
                }else{
                    errorCode('买单失败');
                }
            }
        }else{
            // 获取当前时间戳
            $time = date('YmdHis');
            $ord_id = "E-$time-$uid";
            // 订单数据
            $order = array(
                'body' => '买单', //商品描述（需要根据自己的业务修改）
                'total_fee' => $shg * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
                'out_trade_no' => $ord_id, //订单号（需要根据自己的业务修改）
                'trade_type' => 'JSAPI', //JSAPI公众号支付
                'openid' => $openid //获取到的openid
            );
            // 统一下单 获取prepay_id
            vendor('WeChatPay.XcxPay');
            $pay = new \XcxPay();
            $unified_order = $pay->unifiedOrder($order, config('XCX_CONFIG.CHECK'));
            //数据库生成订单
            $mai = [
                'order' => $ord_id,
                'shop_id' => $id,
                'uid' => $uid,
                'time' => time(),
                'status' => 0,
                'money' => $money,
                'zeng' => $zeng,
                'shi' => $shg,
                'ti' => $ti,
                'type' => 1
            ];
            $re = UserCheck::add($mai);
            if ($re){
                $secret = secret();
                // 组合jssdk需要用到的数据
                $data = array(
                    'appId' => $secret['appid'], //appid
                    'timeStamp' => strval(time()), //时间戳
                    'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
                    'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
                    'signType' => 'MD5'//加密方式
                );
                // 生成签名
                $data['paySign'] = $pay->makeSign($data);
                successCode($data);
            }
        }
    }

    /**
     * 充值
     */
    public function recharge(){
        $openid = input('openid'); //用户openid
        $id = input('id'); //用户id
        $money = input('money'); //充值金额
        // 获取当前时间戳
        $time = date('YmdHis');
        $ord_id = "E-$time-$id";
        // 订单数据
        $order = array(
            'body' => '充值余额', //商品描述（需要根据自己的业务修改）
            'total_fee' => $money * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
            'out_trade_no' => $ord_id, //订单号（需要根据自己的业务修改）
            'trade_type' => 'JSAPI', //JSAPI公众号支付
            'openid' => $openid //获取到的openid
        );
        // 统一下单 获取prepay_id
        vendor('WeChatPay.XcxPay');
        $pay = new \XcxPay();
        $unified_order = $pay->unifiedOrder($order, config('XCX_CONFIG.NOTIFY_URL'));
        //查询当前的充值活动
        $huo = ActivityRecharge::getRechargeInfo(['status' => 1, 'end' => ['gt', time()]], 'lowest, give, cashback');
        if ($huo && $money >= $huo['lowest']){
            $give = $money * $huo['give'] / 100;
            $cashback = $money * $huo['cashback'] / 100;
        }else {
            $give = 0;
            $cashback = 0;
        }
        //数据库生成订单
        $arr = array(
            'order' => $ord_id,
            'uid' => $id,
            'time' => time(),
            'status' => 0,
            'money' => $money,
            'give' => $give,
            'cashback' => $cashback
        );
        $re = UserRecord::add($arr);
        if ($re){
            $secret = secret();
            // 组合jssdk需要用到的数据
            $data = array(
                'appId' => $secret['appid'], //appid
                'timeStamp' => strval(time()), //时间戳
                'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
                'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
                'signType' => 'MD5'//加密方式
            );
            // 生成签名
            $data['paySign'] = $pay->makeSign($data);
            successCode($data);
        }
    }

    /**
     * 查询当前礼包信息并支付
     */
    public function get_mygift(){
        $openid = input('openid'); //用户openid
        $id = input('id'); //大礼包id
        $uid = input('uid'); //用户id
        $yid = input('yid'); //引流商家id
        //查出状态
        $type = GoodsPackage::getField(['id' => $id], 'type');
        if ($type == 0){
            errorCode(['code' => 2]);
        }
        $money = UserChoose::getField(['uid' => $yid, 'package' => $id], 'money');
        //用户是否已经购买
        $is = UserPackage::getUserPackageInfo(['uid' => $uid, 'package' => $id], '');
        if ($money == 0 || $is){
            errorCode(['code' => 0]);
        }else{
            // 获取当前时间戳
            $time = date('YmdHis');
            $ord_id = "E-$time-$id";
            //创建订单
            $order = array(
                'order' => $ord_id, //订单号
                'uid' => $uid, //下单用户
                'pid' => $id, //大礼包id
                'yid' => $yid, //引流商家id
                'time' => time(), //下单时间
                'money' => $money, //订单总额
                'status' => 0, //待付款
            );
            UserPackageRecord::add($order);
            // 订单数据
            $order = array(
                'body' => '购买大礼包', //商品描述（需要根据自己的业务修改）
                'total_fee' => $money * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
                'out_trade_no' => $ord_id, //订单号（需要根据自己的业务修改）
                'trade_type' => 'JSAPI', //JSAPI公众号支付
                'openid' => $openid //获取到的openid
            );
            // 统一下单 获取prepay_id
            vendor('WeChatPay.XcxPay');
            $pay = new \XcxPay();
            $unified_order = $pay->unifiedOrder($order, config('XCX_CONFIG.PACKAGE'));
            $secret = secret();
            // 组合jssdk需要用到的数据
            $data = array(
                'appId' => $secret['appid'], //appid
                'timeStamp' => strval(time()), //时间戳
                'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
                'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
                'signType' => 'MD5'//加密方式
            );
            // 生成签名
            $data['paySign'] = $pay->makeSign($data);
            successCode(['code' => 1, 'data' => $data]);
        }

    }

    /**
     * 拼团订单支付
     */
    public function spell_pay(){
        $id = input('id'); //活动id
        $openid = input('openid'); //用户openid
        $uid = input('uid'); //用户id
        $address = json_decode(input('address'), true); //下单地址
        $message = input('message'); //备注
        $num = input('num'); //参与次数
        $kai = input('kai'); //开团
        $canoid = input('oid'); //开团
        $group = input('group'); //选择的商品参数
        $time = date('YmdHis');
        $ord_id = "$time$uid"; //订单号
        $market = MarketSpell::getSpellInfo(['id' => $id]); //活动
        $product = StoreProduct::getProductInfo(['id' => $market['pid']], ''); //商品
        $order = StoreOrder::getOrder(['id' => $canoid], ''); //订单
        if ($order){
            $count = StoreOrder::countOrder(['spell_number' => $order['spell_number'], 'status' => 1]);
            if ($count >= $market['spell_number']) errorCode('已结束');
        }
        if ($kai == 0 && time() > ($order['time'] + $market['spell_time'])) errorCode('已结束');
        if (!$market || $market['status'] != 1 || !$product || $product['status'] != 0 || $product['is_del'] != 0) errorCode('活动不存在或已下架');
        if ($market['stock'] <= 0) errorCode('已抢完');
        //创建订单
        $order = array(
            'order' => $ord_id, //订单号
            'uid' => $uid, //下单用户
            'time' => time(), //下单时间
            'username' => $address['name'], //收货人
            'phone' => $address['tel'], //收货手机号
            'address' => $address['province'] . $address['city'] . $address['county'] . $address['detail'], //收货详细地址
            'money' => ($kai == 1 ? $market['leader_price'] : $market['spell_price']) * $num + ($market['postage_open'] == 0 ? $market['postage'] : 0), //订单总额 (商品总价加运费)
            'price' => ($kai == 1 ? $market['leader_price'] : $market['spell_price']) * $num,
            'status' => 0, //待付款
            'freight' => $market['postage_open'] == 0 ? $market['postage'] : 0, //运费
            'message' => $message, //用户留言
            'spell_id' => $id,
            'spell_number' => $kai == 1 ? $ord_id : $order['spell_number'],
            'type' => 3
        );
        $oid = StoreOrder::add($order);
        if ($oid){
            $orderlist = [
                'oid' => $oid, //关联订单数据id
                'pid' => $market['pid'], //商品id
                'spec' => $group, //商品规格
                'unit' => $market['original_cost'], //商品单价
                'num' => $num, //购买数量
            ];
            StoreOrderList::add($orderlist);
            MarketSpell::decField(['id' => $id], 'stock', $num); //库存减
            if (($kai == 1 ? $market['leader_price'] : $market['spell_price']) * $num + ($market['postage_open'] == 0 ? $market['postage'] : 0) == 0){
                StoreOrder::upField(['order' => $ord_id], 'status', 1);
                //查出购买订单数据并修改
                $orderlist = StoreOrderList::selOrderList(['oid' => $oid]);
                foreach ($orderlist as $k => $v){
                    MarketBargain::incField(['id' => $id], 'volume', $v['num']); //销量加
                }
                successCode(['code' => 2, 'oid' => $oid]);
            }else{
                // 订单数据
                $order = array(
                    'body' => '购买商品', //商品描述（需要根据自己的业pay_api务修改）
                    'total_fee' => (($kai == 1 ? $market['leader_price'] : $market['spell_price']) * $num + ($market['postage_open'] == 0 ? $market['postage'] : 0)) * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
                    'out_trade_no' => $ord_id, //订单号（需要根据自己的业务修改）
                    'trade_type' => 'JSAPI', //JSAPI公众号支付
                    'openid' => $openid //获取到的openid
                );
                // 统一下单 获取prepay_id
                vendor('WeChatPay.XcxPay');
                $pay = new \XcxPay();
                $unified_order = $pay->unifiedOrder($order, config('XCX_CONFIG.SPELL'));
                $secret = secret();
                // 组合jssdk需要用到的数据
                $data = array(
                    'appId' => $secret['appid'], //appid
                    'timeStamp' => strval(time()), //时间戳
                    'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
                    'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
                    'signType' => 'MD5'//加密方式
                );
                // 生成签名
                $data['paySign'] = $pay->makeSign($data);
                successCode(['code' => 1, 'data' => $data, 'prepay_id' => $unified_order['prepay_id'], 'oid' => $oid]);
            }
        }
    }

    /**
     * 秒杀订单支付
     */
    public function seckill_pay(){
        $id = input('id'); //活动id
        $openid = input('openid'); //用户openid
        $uid = input('uid'); //用户id
        $address = json_decode(input('address'), true); //下单地址
        $message = input('message'); //备注
        $num = input('num'); //参与次数
        $group = input('group'); //选择的商品参数
        $end_time = input('end_time'); //结束时间
        $time = date('YmdHis');
        $ord_id = "$time$uid"; //订单号
        $market = MarketSeckill::getSeckillInfo(['id' => $id]); //活动
        $product = StoreProduct::getProductInfo(['id' => $market['pid']], ''); //商品
        if ($end_time < time()) errorCode('活动已结束');
        if (!$market || $market['status'] != 1 || !$product || $product['status'] != 0 || $product['is_del'] != 0) errorCode('活动不存在或已下架');
        if ($num > $market['once_num']) errorCode('最多单次购买' . $market['once_num'] . '件');
        if ($market['stock'] <= 0) errorCode('已抢完');
        //创建订单
        $order = array(
            'order' => $ord_id, //订单号
            'uid' => $uid, //下单用户
            'time' => time(), //下单时间
            'username' => $address['name'], //收货人
            'phone' => $address['tel'], //收货手机号
            'address' => $address['province'] . $address['city'] . $address['county'] . $address['detail'], //收货详细地址
            'money' => $market['price_spike'] * $num + ($market['postage_open'] == 0 ? $market['postage'] : 0), //订单总额 (商品总价加运费)
            'price' => $market['price_spike'] * $num,
            'status' => 0, //待付款
            'freight' => $market['postage_open'] == 0 ? $market['postage'] : 0, //运费
            'message' => $message, //用户留言
            'seckill_id' => $id,
            'type' => 4
        );
        $oid = StoreOrder::add($order);
        if ($oid){
            $orderlist = [
                'oid' => $oid, //关联订单数据id
                'pid' => $market['pid'], //商品id
                'spec' => $group, //商品规格
                'unit' => $market['original_cost'], //商品单价
                'num' => $num, //购买数量
            ];
            StoreOrderList::add($orderlist);
            MarketSeckill::decField(['id' => $id], 'stock', $num); //库存减
            // 订单数据
            $order = array(
                'body' => '购买商品', //商品描述（需要根据自己的业pay_api务修改）
                'total_fee' => ($market['price_spike'] * $num + ($market['postage_open'] == 0 ? $market['postage'] : 0)) * 100, //订单金额  以(分)为单位（需要根据自己的业务修改）
                'out_trade_no' => $ord_id, //订单号（需要根据自己的业务修改）
                'trade_type' => 'JSAPI', //JSAPI公众号支付
                'openid' => $openid //获取到的openid
            );
            // 统一下单 获取prepay_id
            vendor('WeChatPay.XcxPay');
            $pay = new \XcxPay();
            $unified_order = $pay->unifiedOrder($order, config('XCX_CONFIG.SECKILL'));
            $secret = secret();
            // 组合jssdk需要用到的数据
            $data = array(
                'appId' => $secret['appid'], //appid
                'timeStamp' => strval(time()), //时间戳
                'nonceStr'=> $unified_order['nonce_str'],// 随机字符串
                'package' => 'prepay_id='.$unified_order['prepay_id'],// 预支付交易会话标识
                'signType' => 'MD5'//加密方式
            );
            // 生成签名
            $data['paySign'] = $pay->makeSign($data);
            successCode(['code' => 1, 'data' => $data, 'prepay_id' => $unified_order['prepay_id'], 'oid' => $oid]);
        }
    }
}